package manager;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.DBConnector;
import utils.LockUtil;
import utils.OverlapingUtil;
import utils.Printer;

/**
 * Servlet implementation class AddSessionToCourse
 */
public class AddSessionToCourse extends BaseCMServlet {
	private static final long serialVersionUID = 1L;
	
    
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession(false) == null || request.getSession(false).getAttribute("username") == null){
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Please login first");
			return;
		}
		
		if (!request.getSession(false).getAttribute("type").equals("admin")) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Only Admin can add session to courses");
			return;			
		}
		
		String name = request.getParameter("course_name");
		int day = Integer.parseInt(request.getParameter("day"));
		int start = Integer.parseInt(request.getParameter("start"));
		int end = Integer.parseInt(request.getParameter("end"));		
		
		// TODO: more checking here 
		// TODO: check for overlapping
		if (name         == null || 
		    name.equals("")      || 
			day   < 1            ||
			day   > 7            ||
			start < 9            ||
			end   > 19)
			
		{
			    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "some missing/wrong parameter");
				return;
						
		}
		
		DBConnector dbConn = null;
		try {
			dbConn = new DBConnector();
			
			// Check for overlapping
			PreparedStatement stmnt = dbConn.getConnection().prepareStatement(
					"SELECT c.course_name AS course_name, session_start_time, session_end_time " +
					"FROM courses c, course_sessions cs " + 
					"WHERE c.course_name = cs.course_name AND " +
					"c.group_number = (SELECT group_number FROM courses WHERE course_name = ?) " +
					"AND session_day = ? " +					
					"ORDER BY course_name");
			
			synchronized(LockUtil.getCourseSessionLock()) {
				int i = 1;
				stmnt.setString(i++, name);
				stmnt.setInt(i++, day);
				ResultSet res = stmnt.executeQuery();
				
				OverlapingUtil olu = new OverlapingUtil();
				olu.addSegment(start, end);
				
				while(res.next()) {
					int start_time = res.getInt("session_start_time");
					int end_time = res.getInt("session_end_time");
					
					olu.addSegment(start_time, end_time);
					if (olu.isOverlapping()) {
						break;
					}
				}
				
				if (olu.isOverlapping()) {
					response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Sessions Overlap with course '" + res.getString("course_name") + "'");
					return;
				}
				
				stmnt = dbConn.getConnection().prepareStatement(
						"INSERT INTO course_sessions (course_name, session_day, session_start_time, session_end_time) " +
						"VALUES(?,?,?,?) ");
				
				i = 1;
				stmnt.setString(i++, name);
				stmnt.setInt(i++, day);
				stmnt.setInt(i++, start);						
				stmnt.setInt(i++, end);
				stmnt.executeUpdate();
				
		}
			
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Error");
			return;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		response.sendRedirect("course_details.jsp?course_name=" + name);		
	}
	
	

}
